import { defineStore } from 'pinia';
import axios from '@/plugins/axios';
import { ElMessage } from 'element-plus';

export interface CourseJoin {
  id: number;
  courseId: number;
  studentId: number;
  status: string;
}

export interface CourseJoinRequest {
  courseId: number;
  studentId: number;
}

export interface CourseJoinReviewRequest {
  id: number;
  status: string;
}

export interface CourseJoinUpdateRequest {
  id: number;
  courseId: number;
  studentId: number;
  status: string;
}

export const useCourseJoinStore = defineStore('courseJoin', {
  state: () => ({
    courseJoins: [] as CourseJoin[],
  }),

  actions: {
    async fetchCourseJoins() {
      try {
        const response = await axios.get('/api/course-join');
        this.courseJoins = response.data.data;
        return this.courseJoins;
      } catch (error) {
        ElMessage.error('获取课程加入列表失败');
        throw error;
      }
    },

    async updateCourseJoin(data: CourseJoinUpdateRequest) {
      try {
        const response = await axios.put('/api/course-join', data);
        const index = this.courseJoins.findIndex(item => item.id === data.id);
        if (index !== -1) {
          this.courseJoins[index] = response.data.data;
        }
        ElMessage.success('更新成功');
        return response.data.data;
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '更新失败');
        throw error;
      }
    },

    async reviewCourseJoin(data: CourseJoinReviewRequest) {
      try {
        const response = await axios.post('/api/course-join/review', data);
        const index = this.courseJoins.findIndex(item => item.id === data.id);
        if (index !== -1) {
          this.courseJoins[index] = response.data.data;
        }
        ElMessage.success('审核成功');
        return response.data.data;
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '审核失败');
        throw error;
      }
    },

    async deleteCourseJoin(id: number) {
      try {
        await axios.delete(`/api/course-join/${id}`);
        this.courseJoins = this.courseJoins.filter(item => item.id !== id);
        ElMessage.success('删除成功');
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '删除失败');
        throw error;
      }
    },

    async joinCourse(data: CourseJoinRequest) {
      try {
        const response = await axios.post('/api/course-join', data);
        ElMessage.success('申请加入课程成功');
        return response.data.data;
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '申请加入课程失败');
        throw error;
      }
    },

    async fetchJoinRequestsByStudent(studentId: number) {
      try {
        const response = await axios.get(`/api/course-join/student/${studentId}`);
        return response.data.data;
      } catch (error) {
        ElMessage.error('获取学生加入请求失败');
        throw error;
      }
    },
  },
});